package org.zsl.dao;

import org.zsl.model.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDAO {

    private Connection connection = null;

    private Statement statement = null;
    private PreparedStatement preparedStatement = null;

    private ResultSet resultSet = null;


    private String url = "jdbc:mysql://127.0.0.1:3306/demo";
    private String username = "root";
    private String password = "123456";


    public UserDAO() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(url, username, password);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     *  Q1:如何实现带参数的查询
     * */
    public ResultSet selectAll(){
        String sql = "select * from user";

        try {
            statement = connection.createStatement();
            resultSet=   statement.executeQuery(sql);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return  resultSet;
    }


    public List<User> selectAll2(){
        
       ResultSet resultSet=  this.selectAll();
       List<User> list = new ArrayList<>();
   
           try {
               while (resultSet.next()){

                   User user = covertToUser(resultSet);
                   list.add(user);
               }
           } catch (SQLException throwables) {
               throwables.printStackTrace();
           }


        return list;
        
    }

    private User covertToUser(ResultSet resultSet) throws SQLException {
        User user = new User();
        user.setUsername(resultSet.getString("username"));
        user.setPassword(resultSet.getString("password"));
        user.setRoleId(resultSet.getInt("role_id"));
        return user;
    }

    /**
     *  Q2:如何实现修改和删除
     * */
    public Boolean insert(User user){

        String sql = "insert into user(username,password,role_id) value(?,?,?)";
        Boolean flag= false;

        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,user.getUsername());
            preparedStatement.setString(2,user.getPassword());
            preparedStatement.setInt(3,user.getRoleId());

          flag=   preparedStatement.executeUpdate()>0;

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

       return  flag;
    }
}
